package com.example.knowledgeget1.KnowtCommon.Service;

import com.example.knowledgeget1.KnowtCommon.Entity.Student;
import com.example.knowledgeget1.KnowtCommon.Repository.StudentRepository;
import com.example.knowledgeget1.KnowtCommon.Response.StudentLoginResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class StudentService {
    @Autowired
    private StudentRepository studentRepository;

    // 创建新学生
    public Student createStudent(Student student) {
        return studentRepository.save(student);
    }

    // 获取所有学生
    public List<Student> getAllStudents() {
        return studentRepository.findAll();
    }

    // 通过ID获取单个学生
    public Student getStudentById(Long id) {
        Optional<Student> student = studentRepository.findById(id);
        return student.orElse(null);
    }

    // 验证学生学号和密码，并返回包含学号和token的响应对象
    public Map<String, String> validateStudentAndGetToken(Long stuId, String stuPwd) {
        Optional<Student> student = studentRepository.findById(stuId);
        if (student.isPresent() && student.get().getStuPwd().equals(stuPwd)) {
            String token = generateToken(); // 生成token
            return Map.of("stuId", String.valueOf(stuId), "token", token);
        }
        return null; // 验证失败，返回null
    }

    // 生成token
    private String generateToken() {
        return UUID.randomUUID().toString(); // 使用UUID生成唯一的token
    }

    // 更新学生信息
    public Student updateStudent(Long id, Student studentDetails) {
        Student student = getStudentById(id);
        if (student != null) {
            student.setStuName(studentDetails.getStuName());
            student.setStuPwd(studentDetails.getStuPwd());
            // 更新其他字段...
            studentRepository.save(student);
        }
        return student;
    }

    // 删除学生
    public void deleteStudent(Long id) {
        studentRepository.deleteById(id);
    }
}
